<?php

function EJAddNote(&$noteParams) {
    $aid = "aidAddNote";
    return EJExecuteWithAuthenticatedFamily($aid, $noteParams, function ($fid, $aid, &$noteParams) {
        $postParams = "";
        if (W3GetAPIPostParams($aid, $postParams)) {
            if (EJInsertNote($noteParams, $postParams, $fid)) {
                return W3CreateSuccessfulResult();
            }
        }

        return W3CreateFailedResult();
    });
}

function EJValidatePDF($noteID) {
    $result = shell_exec("./tmp/validate.sh " . $noteID);
    return preg_match("/^TRUE.*/",  $result);
}

function EJGeneratePDF($noteRawData) {
    $result = shell_exec("./tmp/clean.sh");

    $note = $noteRawData["note"];
    $noteDecode = W3Decode($note);
    $noteID = $noteRawData["id"];
    $noteTxtName = "tmp/" . $noteID . ".tex";
    $noteTxt = fopen($noteTxtName, "w");
    if ($noteTxt == FALSE) {
        $errorLog = "Open text file failed";
        W3LogError($errorLog);
        return $errorLog;
    }

    fwrite($noteTxt, $noteDecode);
    fclose($noteTxt);

    $result .= shell_exec("./tmp/pdfgen.sh " . $noteTxtName);
    if (EJValidatePDF($noteID)) {
        return "";
    }

    return $result;
}

function EJGetNote(&$noteParams) {
    $aid = "aidNote";
    return EJExecuteWithAuthenticatedFamily($aid, $noteParams, function ($fid, $aid, &$noteParams) {
        $paramOffset = 1; # The first one is alway whole string from reg match
        $id = $noteParams[W3GetAPIParamIndex($aid, "id") + $paramOffset];

        $sql = "select " .
             "note.ID as id, note.Title as title, note.Tag as tag, note.Note as note, note.Type as type" .
             " from " .
             "note" .
             " where " .
             "note.ID = " . $id .
             " and " .
             "note.FID = " . $fid;

        $result = "{" . W3CreateSuccessfulPartialResult() . "," . W3MakeString(w3ApiResultData) . ":{";
        EJReadTable($sql, function ($row) use (&$result, $aid) {
            $errorLog = "";
            $pdfType = "2";
            if ($row["type"] == $pdfType) {
                $errorLog = EJGeneratePDF($row);
                $errorLog = W3Encode($errorLog);
            }

            $row["error"] = $errorLog;

            $apiDef = W3GetAPIDef($aid);
            $columns = $apiDef[w3ApiResult][w3ApiResultData];
            foreach ($columns as $value) {
                $resultForColumn = $row[$value[w3ApiDataValue]];
                $result .= W3MakeString($value[w3ApiDataValue]) . ":" . W3MakeString($resultForColumn) . ",";
            }
        });
        $result = rtrim($result, ",") . "}}";

        return $result;
    });
}

function EJGetNoteTitle(&$noteParams) {
    $aid = "aidNoteTitle";
    return EJExecuteWithAuthenticatedFamily($aid, $noteParams, function ($fid, $aid, &$noteParams) {
        $paramOffset = 1; # The first one is alway whole string from reg match
        $idTag = $noteParams[W3GetAPIParamIndex($aid, "tag") + $paramOffset];

        $sql = "select " .
             "note.Title as title, note.ID as id" .
             " from " .
             "note" .
             " where " .
             "note.FID = " . $fid .
             " and " .
             "note.Tag = " . $idTag .
             " order by note.Modified desc";

        return EJReadMultiResultFromTable($aid, $sql);
    });
}

function EJModifyNote(&$noteParams) {
    $aid = "aidModifyNote";

    return EJExecuteWithAuthenticatedFamily($aid, $noteParams, function ($fid, $aid, &$noteParams) {
        $postParams = "";
        if (W3GetAPIPostParams($aid, $postParams)) {
            if (EJUpdateNote($noteParams, $postParams, $fid)) {
                return W3CreateSuccessfulResult();
            }
        }

        return W3CreateFailedResult();
    });
}

function EJInsertNote(&$noteParams, &$postParams, $fid) {
    if (!EJConnectDB()) {
        W3LogWarning("No DB connection when insert note");
        return false;
    }

    $columns = array ("Title", "Tag", "Type", "Note", "Modified", "FID");
    $size = sizeof($columns);

    $uselessParamCount = 2; # Match string, session, etc.
    $paramOffset = 1; # 0 is for the whole match string in reg
    if (sizeof($noteParams) + sizeof($postParams) - $uselessParamCount != $size - 1) { # 1 for FID
        W3LogWarning("No enough fields for note insert: require " .
                   strval($size - 2) . # "Modified" not from param, also FID
                   " but actual is " .
                   strval(sizeof($noteParams) - $paramOffset + sizeof($postParams) - $paramOffset));
        return false;
    }

    date_default_timezone_set("Asia/Shanghai");
    $datetime = W3MakeSingleQuotString(date("Y-m-d H:i:s"));
    $aid = "aidAddNote";
    $values = array(W3MakeString($noteParams[W3GetAPIParamIndex($aid, "title") + $paramOffset]),
                    $noteParams[W3GetAPIParamIndex($aid, "tag") + $paramOffset],
                    $noteParams[W3GetAPIParamIndex($aid, "type") + $paramOffset],
                    W3MakeString($postParams[W3GetAPIPostIndex($aid, "note") + $paramOffset]),
                    $datetime,
                    $fid);
    $sql = "insert into note (" . implode(",", $columns) . ") values (" . implode("," , $values) . ")";

    if (!EJExecuteSQL($sql)) {
        W3LogWarning("Execute note insert SQL failed");
        return false;
    }

    return true;
}

function EJUpdateNote(&$noteParams, &$postParams, $fid) {
    if (!EJConnectDB()) {
        W3LogWarning("No DB connection when modify note");
        return false;
    }

    $uselessParamCount = 3; # Match string, session, etc.
    $paramOffset = 1; # 0 is for the whole match string in reg
    $columnCount = 2; # Note, ID
    if (sizeof($noteParams) + sizeof($postParams) - $uselessParamCount != $columnCount) {
        W3LogWarning("No enough fields for note modify: require " .
                   strval($columnCount) .
                   " but actual is " .
                   strval(sizeof($noteParams) - $paramOffset + sizeof($postParams) - $paramOffset));
        return false;
    }

    date_default_timezone_set("Asia/Shanghai");
    $datetime = W3MakeSingleQuotString(date("Y-m-d H:i:s"));
    $aid = "aidModifyNote";
    $newNote = W3MakeString($postParams[W3GetAPIPostIndex($aid, "note") + $paramOffset]);
    $id = $noteParams[W3GetAPIParamIndex($aid, "id") + $paramOffset];

    $sql = "update note set Note=" . $newNote . ", Modified=" . $datetime . "  where ID=" . $id . " and FID=" . $fid;

    if (!EJExecuteSQL($sql)) {
        W3LogWarning("Execute note update SQL failed");
        return false;
    }

    return true;
}

 ?>
